// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <memory>

#include <nebula/io/interfaces.h>

#include <turbo/utility/status.h>
#include <turbo/base/checked_cast.h>
#include <turbo/base/macros.h>

namespace nebula {
namespace io {
namespace internal {

template <class LockType>
class SharedLockGuard {
 public:
  explicit SharedLockGuard(LockType* lock) : lock_(lock) { lock_->LockShared(); }

  ~SharedLockGuard() { lock_->UnlockShared(); }

 protected:
  LockType* lock_;
};

template <class LockType>
class ExclusiveLockGuard {
 public:
  explicit ExclusiveLockGuard(LockType* lock) : lock_(lock) { lock_->LockExclusive(); }

  ~ExclusiveLockGuard() { lock_->UnlockExclusive(); }

 protected:
  LockType* lock_;
};

// Debug concurrency checker that marks "shared" and "exclusive" code sections,
// aborting if the concurrency rules get violated.  Does nothing in release mode.
// Note that we intentionally use the same class declaration in debug and
// release builds in order to avoid runtime failures when e.g. loading a
// release-built DLL with a debug-built application, or the reverse.

class TURBO_EXPORT SharedExclusiveChecker {
 public:
  SharedExclusiveChecker();
  void LockShared();
  void UnlockShared();
  void LockExclusive();
  void UnlockExclusive();

  SharedLockGuard<SharedExclusiveChecker> shared_guard() {
    return SharedLockGuard<SharedExclusiveChecker>(this);
  }

  ExclusiveLockGuard<SharedExclusiveChecker> exclusive_guard() {
    return ExclusiveLockGuard<SharedExclusiveChecker>(this);
  }

 protected:
  struct Impl;
  std::shared_ptr<Impl> impl_;
};

// Concurrency wrappers for IO classes that check the correctness of
// concurrent calls to various methods.  It is not necessary to wrap all
// IO classes with these, only a few core classes that get used in tests.
//
// We're not using virtual inheritance here as virtual bases have poorly
// understood semantic overhead which we'd be passing on to implementers
// and users of these interfaces.  Instead, we just duplicate the method
// wrappers between those two classes.

template <class Derived>
class TURBO_EXPORT InputStreamConcurrencyWrapper : public InputStream {
 public:
  turbo::Status close() final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoClose();
  }

  turbo::Status abort() final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoAbort();
  }

  turbo::Result<int64_t> tell() const final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoTell();
  }

  turbo::Result<int64_t> read(int64_t nbytes, void* out) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoRead(nbytes, out);
  }

  turbo::Result<std::shared_ptr<Buffer>> read(int64_t nbytes) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoRead(nbytes);
  }

  turbo::Result<std::string_view> peek(int64_t nbytes) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoPeek(nbytes);
  }

  /*
  Methods to implement in derived class:

  turbo::Status DoClose();
  turbo::Result<int64_t> DoTell() const;
  turbo::Result<int64_t> DoRead(int64_t nbytes, void* out);
  turbo::Result<std::shared_ptr<Buffer>> DoRead(int64_t nbytes);

  And optionally:

  turbo::Status DoAbort() override;
  turbo::Result<std::string_view> DoPeek(int64_t nbytes) override;

  These methods should be protected in the derived class and
  InputStreamConcurrencyWrapper declared as a friend with

  friend InputStreamConcurrencyWrapper<derived>;
  */

 protected:
  // Default implementations.  They are virtual because the derived class may
  // have derived classes itself.
  virtual turbo::Status DoAbort() { return derived()->DoClose(); }

  virtual turbo::Result<std::string_view> DoPeek(int64_t TURBO_ARG_UNUSED(nbytes)) {
    return turbo::unimplemented_error("peek not implemented");
  }

  Derived* derived() { return ::turbo::checked_cast<Derived*>(this); }

  const Derived* derived() const {
    return ::turbo::checked_cast<const Derived*>(this);
  }

  mutable SharedExclusiveChecker lock_;
};

template <class Derived>
class TURBO_EXPORT RandomAccessFileConcurrencyWrapper : public RandomAccessFile {
 public:
  turbo::Status close() final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoClose();
  }

  turbo::Status abort() final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoAbort();
  }

  turbo::Result<int64_t> tell() const final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoTell();
  }

  turbo::Result<int64_t> read(int64_t nbytes, void* out) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoRead(nbytes, out);
  }

  turbo::Result<std::shared_ptr<Buffer>> read(int64_t nbytes) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoRead(nbytes);
  }

  turbo::Result<std::string_view> peek(int64_t nbytes) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoPeek(nbytes);
  }

  turbo::Status Seek(int64_t position) final {
    auto guard = lock_.exclusive_guard();
    return derived()->DoSeek(position);
  }

  turbo::Result<int64_t> get_size() final {
    auto guard = lock_.shared_guard();
    return derived()->DoGetSize();
  }

  // NOTE: read_at doesn't use stream pointer, but it is allowed to update it
  // (it's the case on Windows when using ReadFileEx).
  // So any method that relies on the current position (even if it doesn't
  // update it, such as peek) cannot run in parallel with read_at and has
  // to use the exclusive_guard.

  turbo::Result<int64_t> read_at(int64_t position, int64_t nbytes, void* out) final {
    auto guard = lock_.shared_guard();
    return derived()->DoReadAt(position, nbytes, out);
  }

  turbo::Result<std::shared_ptr<Buffer>> read_at(int64_t position, int64_t nbytes) final {
    auto guard = lock_.shared_guard();
    return derived()->DoReadAt(position, nbytes);
  }

  /*
  Methods to implement in derived class:

  turbo::Status DoClose();
  turbo::Result<int64_t> DoTell() const;
  turbo::Result<int64_t> DoRead(int64_t nbytes, void* out);
  turbo::Result<std::shared_ptr<Buffer>> DoRead(int64_t nbytes);
  turbo::Status DoSeek(int64_t position);
  turbo::Result<int64_t> DoGetSize()
  turbo::Result<int64_t> DoReadAt(int64_t position, int64_t nbytes, void* out);
  turbo::Result<std::shared_ptr<Buffer>> DoReadAt(int64_t position, int64_t nbytes);

  And optionally:

  turbo::Status DoAbort() override;
  turbo::Result<std::string_view> DoPeek(int64_t nbytes) override;

  These methods should be protected in the derived class and
  RandomAccessFileConcurrencyWrapper declared as a friend with

  friend RandomAccessFileConcurrencyWrapper<derived>;
  */

 protected:
  // Default implementations.  They are virtual because the derived class may
  // have derived classes itself.
  virtual turbo::Status DoAbort() { return derived()->DoClose(); }

  virtual turbo::Result<std::string_view> DoPeek(int64_t TURBO_ARG_UNUSED(nbytes)) {
    return turbo::unimplemented_error("peek not implemented");
  }

  Derived* derived() { return ::turbo::checked_cast<Derived*>(this); }

  const Derived* derived() const {
    return ::turbo::checked_cast<const Derived*>(this);
  }

  mutable SharedExclusiveChecker lock_;
};

}  // namespace internal
}  // namespace io
}  // namespace nebula
